package com.cg.filter;

import com.cg.service.OperateTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * @ClassName OperateTokenFilter
 * @Description 接口幂等性过滤添加删除请求路径
 * @Author CG
 * @Date 2023/12/4 9:47
 **/
public class OperateTokenFilter implements GlobalFilter, Ordered {

    private final Logger logger = LoggerFactory.getLogger(OperateTokenFilter.class);

    @Resource
    private OperateTokenService operateTokenService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取前端请求的路径
        String url = exchange.getRequest().getPath().toString();
        if(url.contains("create") || url.contains("delete") || url.contains("update")){
            //验证是否传参operateToken
            String operateToken = exchange.getRequest().getHeaders().getFirst("operateToken");
            if(operateToken == null || operateToken.equals("")){
                logger.info("operateToken不存在");
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }
            //验证是否在redis中
            Boolean check = operateTokenService.check(operateToken);
            if(!check){
                logger.info("token验证失败");
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }
            //删除
            operateTokenService.deleteToken(operateToken);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 2;
    }
}
